package com.kaka6;

import javax.xml.crypto.Data;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;

public class TestMysql2 {
    public static void main(String[] args) throws Exception {
        //连接上数据库
        Class.forName("com.mysql.jdbc.Driver");
        //获取数据库连接
       Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_maven?useUnicode=true&characterEncoding=utf8",
                "root","");

       //插入的数据
        String username = "数据分析师要写程序";
        int age =100;
        Date birth = new Date();

       //保存数据
        String saveSql = "insert into users(username,age,birth) values(?,?,?)";
        PreparedStatement pstmt = conn.prepareStatement(saveSql);

        //给占位符赋值
        pstmt.setString(1,username);
        pstmt.setInt(2,age);
        pstmt.setObject(3,birth);

        //执行sql语句
        pstmt.executeUpdate();//适合 insert delte update 语句

        //准备sql语句
        String sql = "select id, username, age, birth from users";

        //预编译sql语句
         pstmt = conn.prepareStatement(sql);

        //执行sql语句
        ResultSet rs = pstmt.executeQuery();

        //使用循环的方式从rs中获取数据
        while (rs.next()){
            System.out.print(rs.getInt("id") + "\t");
            System.out.print(rs.getString("username") + "\t");
            System.out.print(rs.getInt("age") + "\t");
            System.out.print(rs.getTimestamp("birth") + "\t");
            System.out.println();
        }
    }
}
